package com.niguang.work.labour.api.controller;


import com.niguang.work.labour.api.entity.Area;
import com.niguang.work.labour.api.service.AreaService;
import com.niguang.work.labour.api.vo.AreaTree;
import com.niguang.work.labour.common.pojo.Result;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 地区 前端控制器
 * </p>
 *
 * @author 83673
 * @since 2018-11-17
 */
@RestController
@RequestMapping("area")
public class AreaController {

    @Autowired
    private AreaService araeService;

    /**
     * 获取整棵树时pid为0
     *
     * @param pid
     * @return
     */
    @GetMapping("getAreaTree")
    public Result getAreaTree(@RequestParam(defaultValue = "0", required = false) int pid) {
        List<Area> list = araeService.list(null);
        Map<Integer, List<AreaTree>> groupBy = list.stream()
                .map(it ->
                        new AreaTree(it.getId(), it.getPid(), it.getAreaName(), null)
                ).collect(Collectors.groupingBy(AreaTree::getPid));
        return Result.success(getTree(groupBy, pid));
    }

    private List<AreaTree> getTree(Map<Integer, List<AreaTree>> group, Integer pid) {
        List<AreaTree> list = group.get(pid);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        list.forEach(it -> it.setChildren(getTree(group, it.getId())));
        return list;
    }

}

